﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Mrhd.Core.Entities;
using Mrhd.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mrhd.Application
{
    public class MobileService : IMobileService, IScoped
    {
        private readonly IRepository<UserMobileEntity> _repository;
        public MobileService(IRepository<UserMobileEntity> repository)
        {
            _repository = repository;
        }

        public async Task<List<BusinessEntity>> GetBindingBusinessAsync(int id)
        {
            var repo = _repository.Change<UserMobileToBusinessEntity>();
            var result = await repo.Include(a => a.Business)
                .Where(a => a.UserId == id)
                .AsNoTracking()
                .Select(a => a.Business)
                .ToListAsync();
            return result;
        }

        public async Task<UserMobileEntity> GrantAsync(UserMobileEntity user)
        {
            var entity = await _repository.FindAsync(user.Id);
            entity.NickName = user.NickName;
            entity.FaceUrl = user.FaceUrl;
            entity.Country = user.Country;
            entity.Province = user.Province;
            entity.City = user.City;
            entity.Gender = user.Gender;
            entity.IsRegister = true;
            await _repository.SaveNowAsync();

            return entity;
        }

        public async Task<List<ProductTypeEntity>> GetMenusAsync()
        {
            var repo = _repository.Change<ProductTypeEntity>();
            var types = await repo.Entities
                .AsNoTracking()
                .Include(a => a.Products.Where(a => !a.IsDeleted))
                .ToListAsync();
            return types;
        }

        public async Task<bool> UpdatePhoneAsync(UserMobileEntity user)
        {
            user.UpdatedTime = DateTimeOffset.Now;
            await _repository.UpdateIncludeAsync(user, new[] { nameof(user.Phone), nameof(user.UpdatedTime) });
            return true;
        }

    }
}
